import {
	createWebSocket,
	sendSock,
	webSock,
	closeSock,
	websocketOnMessage,
} from "@/utils/websocketManager";
import { nextTick } from "vue";

const  websocketStore = defineStore('websocket', () => {
	/**
	 * socket推送过来的全量数据，暴露出去用户对数据变更的监听
	 */
	
	const serviceMsg = ref({});
	const ws = ref(null);
	const audioGo = ref(false);
	const imgGo = ref(false);
	const duration=ref(0)
	/**
	 * 连接webSocket init
	 */
	const init = () => {
		createWebSocket(global_callback);
		nextTick(() => {
			ws.value = webSock;
		});
	};
 
	/**
	 * websocket的回调函数
	 * @param jsonMsg 表示收到的消息
	 */
	const global_callback = (jsonMsg, type,time) => {
	
		serviceMsg.value = jsonMsg;
		if (type == 'audio') {
			if (audioGo.value) {
				audioGo.value=false
			} else {
				audioGo.value=true
			}
			console.log("声音时长：",Number(time))
			duration.value = Number(time)
			
		}
		if (type == 'img') {
			// audioGo.value = false;
			imgGo.value = true;
			// duration.value=0
		}
		
	};
 
	/**
	 * webSocket发送消息
	 * @param sendData 发送的json数据
	 */
	const send = (sendData) => {
		sendSock(JSON.stringify(sendData));
	};
 
	/**
	 * 关闭webSocket
	 */
	const close = ({ isActiveClose = false }) => {
		console.log(isActiveClose,"isActiveCloseisActiveCloseisActiveClose")
		closeSock({ activeClose: isActiveClose });
	};
 
	/**
	 * 关闭后重启socket
	 */
	const closeAndRestart = () => {
		close({ isActiveClose: true });
		init();
	};
	const cleanAudioAndImg = (data) => {
		
		imgGo.value = data;
		audioGo.value = data;
		if (!data) {
			ws.value.imageQueue=''
		}
	};
	return {
		init,
		close,
		closeAndRestart,
		cleanAudioAndImg,
		serviceMsg,
		ws,
		audioGo,
		imgGo,
		duration
	};
});

export default websocketStore;